package com.zhan.rkforum.service;


import com.zhan.rkforum.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings("all")
public class LikeServiceImpl implements LikeService{


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    @Override
    public Long getEntityLikeCount(int entityType, int entityId) {
        String key = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        return redisTemplate.opsForSet().size(key);
    }

    @Override
    public void like(int entityType, int entityId, int userId) {

//        String key  = LikeKeyUtil.getEntityLikeKey(entityType, entityId);
//        boolean isMember = redisTemplate.opsForSet().isMember(key, String.valueOf(userId));
//        if(isMember){
//            redisTemplate.opsForSet().remove(key, String.valueOf(userId));
//        }else {
//            redisTemplate.opsForSet().add(key,String.valueOf(userId));
//        }


        //Redis事务操作
        redisTemplate.execute(new SessionCallback() {
            @Override
            public  Object execute(RedisOperations redisOperations) throws DataAccessException {
                String key = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
                boolean isMember = redisTemplate.opsForSet().isMember(key, String.valueOf(userId));
                redisOperations.multi();
                if (isMember) {
                    redisTemplate.opsForSet().remove(key, String.valueOf(userId));
                    redisTemplate.opsForValue().decrement(RedisKeyUtil.getUserLikeKey( userId));
                } else {
                    redisTemplate.opsForSet().add(key, String.valueOf(userId));
                    redisTemplate.opsForValue().increment(RedisKeyUtil.getUserLikeKey(userId));
                }
                return redisOperations.exec();
            }
        });
    }

    @Override
    public int getLikeStatus(int entityType, int entityId, int userId) {
        String key  = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
        int stuatus = redisTemplate.opsForSet().isMember(key, String.valueOf(userId)) ? 1 : 0;
        return stuatus;
    }

    @Override
    public int getUserLikeCount(int userId) {
        String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
        String num = (String)redisTemplate.opsForValue().get(userLikeKey);
        if(StringUtils.isBlank(num)){
            redisTemplate.opsForValue().set(userLikeKey,"0");
            num = (String) redisTemplate.opsForValue().get(userLikeKey);
        }
        return Integer.parseInt(num);
    }
}
